package com.message.tcp.ip.socket.configure.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.message.tcp.ip.socket.configure.entity.TxnDef;
import com.message.tcp.ip.socket.util.SqliteConnection;
@Repository("txnDefDao")
public class TxnDefDaoImp implements TxnDefDao {

	@Override
	public void save(TxnDef txnDef) throws SQLException {
		String sql = "INSERT INTO TXNDEF (MTI,TAG,TXNCODE,DENUM,FLAG,DEVAL,PATT) VALUES (?,?,?,?,?,?,?)";
		Connection conn = SqliteConnection.getConnection();
		PreparedStatement stat = conn.prepareStatement(sql); 
		stat.setString(1, txnDef.getMti());
		stat.setString(2, txnDef.getTag());
		stat.setString(3, txnDef.getTxnCode());
		stat.setInt(4, txnDef.getDe());
		stat.setString(5, txnDef.getFlag());
		stat.setString(6, txnDef.getDeVal());
		stat.setString(7, txnDef.getPattern());
		stat.execute();
	}

	@Override
	public void saveList(List<TxnDef> list) throws SQLException {
		String sql = "INSERT INTO TXNDEF (MTI,TAG,TXNCODE,DENUM,FLAG,DEVAL,PATT) VALUES (?,?,?,?,?,?,?)";
		Connection conn = SqliteConnection.getConnection();
		conn.setAutoCommit(false);
		conn.setSavepoint();
		PreparedStatement stat = conn.prepareStatement(sql);
		for(TxnDef txnDef : list){
			stat.setString(1, txnDef.getMti());
			stat.setString(2, txnDef.getTag());
			stat.setString(3, txnDef.getTxnCode());
			stat.setInt(4, txnDef.getDe());
			stat.setString(5, txnDef.getFlag());
			stat.setString(6, txnDef.getDeVal());
			stat.setString(7, txnDef.getPattern());
			stat.execute();
		}
		conn.commit();
	}
	
	@Override
	public List<TxnDef> getTxnDefList(TxnDef txnDef) throws SQLException{
		String sql = "SELECT ID, MTI, TAG, CODE, DENUM, FLAG, PATT FROM TXNDEF WHERE CODE = ? ";
		Connection conn = SqliteConnection.getConnection();
		PreparedStatement stat = conn.prepareStatement(sql);
		stat.setString(1, txnDef.getTxnCode());
		ResultSet rs = stat.executeQuery();
		List<TxnDef> list = new ArrayList<TxnDef>();
		while(rs.next()){
			int id = rs.getInt("ID");
			String mti = rs.getString("MTI");
			String tag = rs.getString("TAG");
			String code = rs.getString("CODE");
			int de = rs.getInt("DENUM");
			String flag = rs.getString("FLAG");
			String patt = rs.getString("PATT");
			
			TxnDef td = new TxnDef();
			td.setId(id);
			td.setMti(mti);
			td.setTag(tag);
			td.setTxnCode(code);
			td.setDe(de);
			td.setFlag(flag);
			td.setPattern(patt);
			list.add(td);
		}
		return list;
	}

}
